# -*- coding: utf-8 -*-
import os
from MsgProcess import MsgProcess, MsgType
import RPi.GPIO as GPIO
import time

#低音
CL = [

0,
#12   1   1#
	262, 277, 
#34   2   2#
	293, 311, 
#5    3   
	329,
#67   4   4#
	349, 370,
#89   5   5#
	392, 415,
#1011 6   6#
	440, 466,
#12   7
	492

	]


#中音
CM = [

0,
#12   1   1#
	523, 553, 
#34   2   2#
	586, 621, 
#5    3   
	658,
#67   4   4#
	697, 739,
#89   5   5#
	783, 830,
#1011 6   6#
	879, 931,
#12   7
	987


]

#高音
CH = [

0,
#12   1   1#
	1045, 1106, 
#34   2   2#
    1171, 1241, 
#5    3   
	1316,
#67   4   4#
	1393, 1476,
#89   5   5#
	1563, 1658,
#1011 6   6#
	1755, 1860,
#12   7
	1971
]
#谱子频率
song = [

CL[1], CL[3], CL[5], CL[6], CL[8], CL[10], CL[12] ,

]

#全音符时长
time_time= 3
y=time_time
y2=time_time/2
y4=time_time/4
y8=time_time/8
y16=time_time/16

beat = [

		y4, y4, y4, y4, y4, y4, y4, 


]
 

class Buzzer(MsgProcess):
    # 初始化操作
    Buzzer=37
    def setup(self):
        
        GPIO.setwarnings(False)       
        GPIO.setmode(GPIO.BOARD)		
        GPIO.setup(self.Buzzer, GPIO.OUT)		
        self.Buzz = GPIO.PWM(self.Buzzer, 440)	
        self.Buzz.start(50)					


    def Text(self, message):  
        data = message["Data"]
        self.setup()
        if "测试" in data:
            for i in range(0, len(song)):
                if song[i]==None:
                    self.Buzz.ChangeFrequency(1)
                else:
                    self.Buzz.ChangeFrequency(song[i])
                time.sleep(beat[i])
        elif "警报" in data:
            i=1000#频率
            dirs =1#频率递增方向，1为正，-1为负
            for x in range(400):
                self.Buzz.ChangeFrequency(i)#为设置的新频率，单位为 Hz
                i=i+10*dirs#当前频率加上要增加的频率(10)乘以方向
                time.sleep(0.02)#延时
                #print('pwm当前频率为: %d '% i)#控制台打印当前的频率
                if i>=2000:#如果当前频率大于2000hz，方向改为负
                    dirs = -1
                elif i<=1000:#如果当前频率小于1000hz，方向改为正
                    dirs = 1

        self.Buzz.stop()
        GPIO.output(self.Buzzer, 1)
        GPIO.cleanup()			
        